<template>
  <div>
    <a-form-item-rest>
      <div v-for="(param, index) in dynamicInput.params" :key="index" style="display: flex">
        <a-input :placeholder="keyPlaceholder" :readonly="readonly" v-model:value="param.label" style="width: 40%; margin-bottom: 5px" @input="emitChange" />
        <a-input 
          v-bind="valueProps"
          v-if="valueComponentType == 'Input'" :placeholder="valuePlaceholder" 
          :readonly="readonly" v-model:value="param.value" style="width: 40%; margin: 0 0 5px 5px" 
          @input="emitChange" 
        />
        <a-input-number 
          v-bind="valueProps"
          v-if="valueComponentType == 'InputNumber'" :placeholder="valuePlaceholder" 
          :readonly="readonly" v-model:value="param.value" style="width: 40%; margin: 0 0 5px 5px" 
          @input="emitChange" 
        />
        <MinusCircleOutlined v-if="dynamicInput.params.length > min && !readonly" class="dynamic-delete-button" @click="remove(param)" style="width: 50px" />
      </div>
      <div v-if="showAddButton">
        <a-button type="dashed" style="width: 80%" @click="add">
          <PlusOutlined />
          新增
        </a-button>
      </div>
    </a-form-item-rest>
  </div>
</template>
<script lang="ts">
  import { MinusCircleOutlined, PlusOutlined } from "@ant-design/icons-vue"
  import { defineComponent, reactive, ref, UnwrapRef, watchEffect } from "vue"
  import { propTypes } from "/@/utils/propTypes"
  import { isEmpty } from "/@/utils/is"
  import { useAttrs } from "/@/hooks/core/useAttrs"
  import { tryOnMounted, tryOnUnmounted } from "@vueuse/core"
  interface Params {
    label: string
    value: string
  }

  export default defineComponent({
    name: "JAddInput",
    props: {
      value: propTypes.string.def(""),
      valueComponentType: propTypes.string.def("Input"),
      valueProps: propTypes.object.def({}),
      showAddButton: propTypes.bool.def(true),
      keyPlaceholder: propTypes.string.def('请输入参数key'),
      valuePlaceholder: propTypes.string.def('请输入参数value'),
      readonly: propTypes.bool.def(false),
      // 是否为数组结构
      isArray: propTypes.bool.def(false),
      fieldKeyName: propTypes.string.def('key'),
      fieldValueName: propTypes.string.def('value'),
      //系统编码规则，最后一个输入框不能删除
      //自定义删除按钮多少才会显示
      min: propTypes.integer.def(1),
    },
    emits: ["change", "update:value"],
    setup(props, { emit }) {
      const attrs = useAttrs()
      //input动态数据
      const dynamicInput: UnwrapRef<{ params: Params[] }> = reactive({ params: [] })
      //删除Input
      const remove = (item: Params) => {
        let index = dynamicInput.params.indexOf(item)
        if (index !== -1) {
          dynamicInput.params.splice(index, 1)
        }
        emitChange()
      }
      //新增Input
      const add = () => {
        dynamicInput.params.push({
          label: "",
          value: "",
        })
        emitChange()
      }

      //监听传入数据value
      watchEffect(() => {
        initVal()
      })

      /**
       * 初始化数值
       */
      function initVal() {
        console.log("props.value", props.value)
        dynamicInput.params = []
        if (props.value && props.value.indexOf("{") == 0) {
          let jsonObj = JSON.parse(props.value)
          Object.keys(jsonObj).forEach((key) => {
            dynamicInput.params.push({ label: key, value: jsonObj[key] })
          })
        } else if (props.value && props.value.indexOf("[") == 0) {
          let array = JSON.parse(props.value)
          array.forEach((item) => {
            dynamicInput.params.push({ label: item[props.fieldKeyName], value: item[props.fieldValueName] })
          })
  
        }
      }
      /**
       * 数值改变
       */
      function emitChange() {
        if(props.isArray) {
          let array = []
          if (dynamicInput.params.length > 0) {
            dynamicInput.params.forEach((item) => {
              const obj : any = {}
              obj[props.fieldKeyName] = item.label
              obj[props.fieldValueName] = item.value
              array.push(obj)
            })
          }
          emit("change", JSON.stringify(array))
          emit("update:value", JSON.stringify(array))
        } else {
          let obj = {}
          if (dynamicInput.params.length > 0) {
            dynamicInput.params.forEach((item) => {
              obj[item["label"]] = item["value"]
            })
          }
          emit("change", isEmpty(obj) ? "" : JSON.stringify(obj))
          emit("update:value", isEmpty(obj) ? "" : JSON.stringify(obj))
        }
      }

      return {
        dynamicInput,
        emitChange,
        remove,
        add,
        attrs
      }
    },
    components: {
      MinusCircleOutlined,
      PlusOutlined,
    },
  })
</script>
<style scoped>
  .dynamic-delete-button {
    cursor: pointer;
    position: relative;
    bottom: 2px;
    left: 5px;
    font-size: 24px;
    color: #999;
    transition: all 0.3s;
  }

  .dynamic-delete-button:hover {
    color: #777;
  }

  .dynamic-delete-button[disabled] {
    cursor: not-allowed;
    opacity: 0.5;
  }
</style>
